<template>
  <div class="class-create-root">

    <!-- @closed 窗口关闭时结束时的回调   -->
    <el-drawer v-model="employmentStore.employmentStoreDialogVisible" :title="className" size="600"
               @closed="toggleDialog"
               style="text-align: center;font-weight:bold;"
    >

      <el-form
          ref="ruleFormRef"
          style="max-width: 600px"
          :model="ruleForm"
          :rules="rules"
          label-width="auto"
          class="demo-ruleForm"
          :size="formSize"
          status-icon
      >
        <el-form-item label="学员姓名" prop="student_id">
          <el-select v-model="ruleForm.student_id" placeholder="请选择学员">
            <el-option v-for="item in studentList"
                       :key="item.id"
                       :label="item.name"
                       :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="入职时间" required>
          <el-form-item prop="entry_date">
            <el-date-picker
                v-model="ruleForm.entry_date"
                type="date"
                value-format="YYYYMMDD"
                placeholder="选择一个日期"
                style="width: 100%"
            />
          </el-form-item>
        </el-form-item>
        <el-form-item label="所在城市" prop="work_location">
<!--          v-model="ruleForm.work_location"-->
          <area-select
              v-model:model-value="ruleForm.work_location"
          />

        </el-form-item>
        <el-form-item label="入职公司" prop="company_name" required>
          <el-input v-model="ruleForm.company_name" />
        </el-form-item>
        <el-form-item label="入职岗位" prop="station" required>
          <el-input v-model="ruleForm.station" />
        </el-form-item>
        <el-form-item label="薪资" prop="salary" required>
          <el-input type="number" v-model="ruleForm.salary" />
        </el-form-item>
        <el-form-item label="入职通知书" prop="offer">
          <el-upload
              ref="ruleForm.offer"
              class="upload-demo"
              action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
              :on-change="handleChange"
              :before-upload="handleBeforeUpload"
              :on-remove="handleRemoveFile"
              :limit="1"
              :auto-upload="false"
          >
            <template #trigger>
<!--              <el-button v-if="ruleForm.offer!=='' && ruleForm.action_type !== EMPLOYMENT_ACTION.ADD" type="primary" @click="showVideo(ruleForm.offer)">预览</el-button>-->
              <el-button type="primary">选择文件</el-button>
            </template>
          </el-upload>
          <img v-if="ruleForm.offerUrl" :src="ruleForm.offerUrl" alt="预览" />
        </el-form-item>
        <el-form-item label="学员选择" prop="is_entry">
          <el-switch
              v-model="ruleForm.is_entry"
              :active-value="2"
              :inactive-value="1"
              active-color="#13ce66"
              inactive-color="#ff4949"
              active-text="放弃"
              inactive-text="入职"
          ></el-switch>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            提交
          </el-button>
          <el-button @click="resetForm(ruleFormRef)">重置</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>

<script setup>
import {reactive, ref} from 'vue'
import {useEmploymentStore} from "@/store/store-employment";
import EventBus from "@/plugins/event-bus";
import {ElMessage} from 'element-plus'
import {
  addStudentEmploymentAPI,
  updateStudentEmploymentAPI
} from "@/network/employment/employment";
import AreaSelect from "@/components/common/AreaSelect.vue";
import {EMPLOYMENT_ACTION} from "@/dict/dict-employment";


const employmentStore = useEmploymentStore();

const handleRemoveFile = () => {
  ruleForm.value.offerUrl = ""
};

const handleBeforeUpload = (file) => {
  if (file.raw ) {
    const reader = new FileReader();
    reader.onload = (e) => {
      // ruleForm.value.offer = e.target.result;
      ruleForm.value.offerUrl = e.target.result;
    };
    reader.readAsDataURL(file.raw);
    return false; // 阻止默认上传
  } else {
    ElMessage.error('请选择一个图片文件');
    return false; // 阻止默认上传
  }
};


// 文件选择时触发
const handleChange = (file) => {
  if (file.status === 'ready') {
    handleBeforeUpload(file);
  }
  if (ruleForm.value.action_type === EMPLOYMENT_ACTION.UPDATE) {
    updateFileFlag.value = true
  }
  ruleForm.value.offer = file
};

const resetForm = (formEl) => {
  if (!formEl) return
  formEl.resetFields()
}

const toggleDialog = () => {
  employmentStore.toggleEmploymentStoreDialogVisible();
};

let studentList = ref([])
let classId = ref()
let className = ref("")
let studentId = ref()
let updateFileFlag = ref(false)
// 监听学生列表改变
EventBus.on("student-list-event", (data) => {
  studentList.value = data;
})

EventBus.on("add-employment-data-event",(eventAddData)=>{
  ruleForm.value.action_type = eventAddData.actionType;
  ruleForm.value.offerUrl = eventAddData.offer
  classId.value = eventAddData.classId
  className.value = eventAddData.className + "就业信息录入"
})

EventBus.on("update-employment-data-event",(eventUpdateData)=>{
  // 面试信息id，更新需要传这个数据
  studentId.value = eventUpdateData.student_id
  ruleForm.value.action_type = eventUpdateData.actionType;
  ruleForm.value.id = eventUpdateData.id;
  ruleForm.value.student_id = eventUpdateData.student_id;
  ruleForm.value.company_name = eventUpdateData.company_name;
  ruleForm.value.entry_date = eventUpdateData.entry_date;
  if (eventUpdateData.offer !== ""){
    ruleForm.value.offerUrl = process.env.VUE_APP_BASE_FILE_URL + eventUpdateData.offer
  }
  else {
    ruleForm.value.offerUrl = eventUpdateData.offer;
  }
  ruleForm.value.offer = eventUpdateData.offer
  ruleForm.value.work_location = JSON.parse(eventUpdateData.work_location);
  ruleForm.value.salary = eventUpdateData.salary;
  ruleForm.value.station = eventUpdateData.station;
  ruleForm.value.is_entry = eventUpdateData.is_entry;
})


const formSize = ref('default')
const ruleFormRef = ref("")
const ruleForm = ref({
  student_id: '',
  entry_date: '',
  company_name: '',
  offer: '',
  work_location: {province:'', city:''},
  salary: '',
  station: '',
  is_entry:'',
})

const rules = reactive({
  work_location: [
    {
      required: true,
      message: '请选择城市',
      trigger: 'blur',
    },
  ],
  entry_date: [
    {
      required: true,
      message: '请选择日期',
      trigger: 'blur',
    },
  ],
})

const submitForm = (formEl) => {
  if (!formEl) return
  formEl.validate((valid, fields) => {
    if (valid) {
      let data = {
        student_id: ruleForm.value.student_id,
        entry_date: ruleForm.value.entry_date,
        company_name: ruleForm.value.company_name,
        offer: ruleForm.value.offer,
        work_location: JSON.stringify(ruleForm.value.work_location),
        salary: ruleForm.value.salary,
        station: ruleForm.value.station,
        is_entry: ruleForm.value.is_entry,
       }
      if(ruleForm.value.action_type === EMPLOYMENT_ACTION.ADD){
        studentId.value = data.student_id
        addStudentEmploymentAPI(data).then((res)=>{
          if (res.data.code !== 0) {
            ElMessage.error(res.data.message)
          }
          else {
            ElMessage.success(res.data.message)
            resetForm(formEl)
            employmentStore.toggleEmploymentStoreDialogVisible()
          }
        })
      }
      else if (ruleForm.value.action_type === EMPLOYMENT_ACTION.UPDATE){
        data.id = ruleForm.value.id;
        updateStudentEmploymentAPI(data, updateFileFlag.value).then((res)=>{
          if(res.data.code!=0){
            ElMessage.error(res.data.message)
          }else{
            ElMessage.success(res.data.message);
            resetForm(formEl)
            employmentStore.toggleEmploymentStoreDialogVisible()
          }
        })
      }
      EventBus.emit("refresh-employment-list-event", data)
    } else {
      console.log('error submit!', fields)
    }
  })
}


</script>

<style scoped lang="less">
.class-create-root {
}
</style>